package com.alibaba.cloud.tech.mq;

import com.alibaba.cloud.tech.constant.TechConstant;
import com.alibaba.cloud.tech.entity.TechSheet;
import com.alibaba.cloud.tech.service.TechSheetService;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class TechListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(TechListener.class);

    @Autowired
    private TechSheetService techSheetService;

    @RabbitListener(queues = TechConstant.TECH_QUEUE)
    public void techSheetListener(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            TechSheet techSheet = JSON.parseObject(message.getBody(), TechSheet.class);
            LOGGER.info("Tech@收到消息：{}", techSheet.toString());
            LOGGER.info("RabbitMq@DeliveryTag：{}", deliveryTag);
            techSheetService.add(techSheet);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("检验检查申请保存失败!");
        }

        try {
            channel.basicAck(deliveryTag, false);
            LOGGER.info("收到消息已确认!");
        } catch (IOException e) {
            e.printStackTrace();
            channel.basicNack(deliveryTag, false, false);
            LOGGER.error("消息已拒绝!");
        }
    }
}
